package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.SysArtist;
import com.ruoyi.system.domain.SysArtistExt;
import com.ruoyi.system.domain.SysArtistProject;
import com.ruoyi.system.domain.SysProject;
import com.ruoyi.system.mapper.SysArtistExtMapper;
import com.ruoyi.system.mapper.SysArtistProjectMapper;
import com.ruoyi.system.mapper.SysProjectMapper;
import com.ruoyi.system.service.impl.SysArtistProjectServiceImpl;
import com.ruoyi.system.service.impl.SysArtistServiceImpl;
import com.ruoyi.system.service.impl.SysProjectServiceImpl;
import com.ruoyi.web.apimodel.system.candidate.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Creater Yaphets
 * time 2024/6/22 0022:18:31
 * package com.ruoyi.web.controller.system
 */


//业务逻辑应放service，后续再优化了。
@Api(tags = "候选人管理")
@RestController
@RequestMapping("/system/candidate")
public class SysCandidateController extends BaseController {

    @Autowired
    SysArtistServiceImpl sysArtistService;

    @Autowired
    SysProjectServiceImpl sysProjectService;

    @Autowired
    SysArtistProjectServiceImpl sysArtistProjectService;

    @Autowired
    SysArtistExtMapper sysArtistExtMapper;


    /**
     * 查询项目候选人
     * @param candidateSearch
     * @return
     */
    @ApiOperation("查询项目候选人")
    @ApiResponse(code = 200, message = "查询项目候选人")
    @PostMapping("list")
    public TableDataInfo getList(@RequestBody CandidateSearch candidateSearch){
        if(candidateSearch.getProjectId()==null){
            return getDataTable(new ArrayList<>());
        }
        //自定义条件过滤
        //1、先过滤人员标签数据
        List<Long> user_ids = new ArrayList<>();
        if(candidateSearch.getLabs()!=null && candidateSearch.getLabs().length>0){
            SysArtist sysArtist = new SysArtist();
            sysArtist.setLabs(candidateSearch.getLabs());
            user_ids = sysArtistService.selectSysArtistList(sysArtist).stream().map(SysArtist::getId).collect(Collectors.toList());
        }
        //2按关系实例的条件过滤
        List<SysArtistProject> relation =  new ArrayList<>();
        List<SysArtistProject> relationScore =  new ArrayList<>();
        List<SysArtistProject> relationScoreTotal =  new ArrayList<>();
        List<SysArtistProject> res =  new ArrayList<>();
        SysArtistProject sysArtistProject = new SysArtistProject();
        sysArtistProject.setProjectId(candidateSearch.getProjectId());
        sysArtistProject.setPassStatus(candidateSearch.getPassStatus());
        List<SysArtistProject> all =  sysArtistProjectService.selectSysArtistProjectList(sysArtistProject);
        if(candidateSearch.getDimension()!=null && candidateSearch.getComparison()!=null){
            relationScore  = sysArtistProjectService.filterByDimension(all,candidateSearch.getDimension(),candidateSearch.getComparison(),candidateSearch.getScore());
        }
        if(candidateSearch.getScoreTotalComparison()!=null ){
            relationScoreTotal = sysArtistProjectService.filterByScoreTotal(all,candidateSearch.getScoreTotalComparison(),candidateSearch.getScoreTotal());
        }

        if(candidateSearch.getScoreTotalComparison()!=null && candidateSearch.getComparison()!=null){
            relation = relationScore.stream().filter(relationScoreTotal::contains).distinct().collect(Collectors.toList());
        } else if(candidateSearch.getScoreTotalComparison()!=null){
            relation = relationScoreTotal;
        } else if(candidateSearch.getComparison()!=null){
            relation =  relationScore;
        } else {
            relation = all;
        }

        //3、根据人员标签和关系实例的交集，获取人员列表
        if(!user_ids.isEmpty()){
            List<Long> finalUser_ids = user_ids;
            List<SysArtistProject> sysArtistList = relation.stream().filter(item -> finalUser_ids.contains( item.getArtistId())).collect(Collectors.toList());
            startPage();
            return getDataTable(sysArtistList);
        } else {
            startPage();
            return getDataTable(relation);
        }
    }

    /**
     * 新增候选人列表
     * @param
     * @return
     */
    @ApiOperation("新增候选人列表")
    @ApiResponse(code = 200, message = "新增候选人列表")
    @PostMapping("list/getAddList")
    public TableDataInfo getAddList(@RequestBody CandidateSearch candidateSearch){

        SysArtist sysArtist = new SysArtist();
        List<SysArtist> list = sysArtistService.selectSysArtistList(sysArtist);
        //过滤出没有关联项目的人员
        if(!list.isEmpty()){
            List<SysArtist> res = new ArrayList<>();
            List<SysArtist>  res1 = list.stream().filter(item->!Arrays.asList(item.getProjectIds()).contains(candidateSearch.getProjectId())).collect(Collectors.toList());
            List<Long> labs = Arrays.asList(candidateSearch.getLabs());
            if(!labs.isEmpty()){
               for (Long labId:labs){
                   res.addAll(res1.stream().filter(item-> item.getLabs()!=null && Arrays.asList(item.getLabs()).contains(labId)).collect(Collectors.toList()));
               }
            }else {
                res = res1;
            }
            startPage(candidateSearch);
            return getDataTable(res);
        }
        startPage(candidateSearch);
        return getDataTable(list);
    }


    /**
     * 添加候选人
     * @param add {"projectId":1,"artistIds":[1,2]}
     * @return
     */
    @ApiOperation("添加候选人")
    @ApiResponse(code = 200, message = "添加候选人")
    @PostMapping("list/add")
    public AjaxResult add(@RequestBody CandidateAdd add){
        SysProject sysProject =  sysProjectService.selectSysProjectById(add.getProjectId());
        Long[]  artistId = add.getArtistIds();
        if(sysProject!=null && artistId!=null && artistId.length>0){
            for (Long id: artistId) {
                SysArtistProject sysArtistProject = new SysArtistProject();
                sysArtistProject.setProjectId(add.getProjectId());
                sysArtistProject.setArtistId(id);
                sysArtistProject.setProjectInfo(sysProject.getProjectInfo());
                sysArtistProject.setProjectScore(sysProject.getProjectScore());
                sysArtistProjectService.insertSysArtistProject(sysArtistProject);
            }
        }else {
            return error("参数错误");
        }
        return success();
    }


    /**
     * 删除候选人
     * @param  del {"projectId":1,"artistId":1}
     * @return
     */
    @ApiOperation("删除候选人")
    @ApiResponse(code = 200, message = "删除候选人")
    @PostMapping("list/del")
    public AjaxResult del(@RequestBody CandidateDel del){
        SysArtistProject sysArtistProject = sysArtistProjectService.selectSysArtistProjectByTowId(del.getArtistId(),del.getProjectId());
//        Long id = sysArtistProjectService.selectSysArtistProjectList(sysArtistProject).get(0).getId();
        Long id = sysArtistProject.getId();
        sysArtistProjectService.deleteSysArtistProjectById(id);
        return success();
    }

    /**
     * 候选人评分
     * @param score {"projectId":1,"artistId":1,"projectScore":"[{\"key\": \"速度\", \"value\": \"\"}, {\"key\": \"精准度\", \"value\": \"\"}]"}
     * @return
     */
    @ApiOperation("候选人评分")
    @ApiResponse(code = 200, message = "候选人评分")
    @PostMapping("list/score")
    public AjaxResult score(@RequestBody CandidateScore score){
        SysArtistProject sysArtistProject = sysArtistProjectService.selectSysArtistProjectByTowId(score.getArtistId(),score.getProjectId());
        sysArtistProject.setProjectScore(score.getProjectScore());
        sysArtistProject.setProjectScoreTotal(sysArtistProjectService.getScoreTotalValue(score.getProjectScore()));
        sysArtistProjectService.updateSysArtistProject(sysArtistProject);
        return success();
    }


    @ApiOperation("修改候选人")
    @ApiResponse(code = 200, message = "修改候选人")
    @PostMapping("list/editCandidate")
    @Transactional
    public AjaxResult editCandidate(@RequestBody CandidateEditArtist candidateEditArtist){
        SysArtistProject sysArtistProject = sysArtistProjectService.selectSysArtistProjectByTowId(candidateEditArtist.getArtistId(),candidateEditArtist.getProjectId());
        sysArtistProject.setProjectInfo(candidateEditArtist.getProjectInfo());
        sysArtistProjectService.updateSysArtistProject(sysArtistProject);
        SysArtist artist = JSON.parseObject(JSON.toJSONString(candidateEditArtist), SysArtist.class);
        artist.setId(candidateEditArtist.getArtistId());
        sysArtistService.updateSysArtist(artist);
        return success("修改候选人成功");
    }

    /**
     * 查看候选人评分
     * @param info {"projectId":1,"artistId":1}
     * @return
     */
    @ApiOperation("查看候选人评分")
    @ApiResponse(code = 200, message = "查看候选人评分")
    @PostMapping("list/scoreInfo")
    public AjaxResult scoreInfo(@RequestBody CandidateScoreInfo info){
        SysArtistProject sysArtistProject = sysArtistProjectService.selectSysArtistProjectByTowId(info.getArtistId(), info.getProjectId());
        SysArtistProject row = sysArtistProjectService.selectSysArtistProjectList(sysArtistProject).get(0);
        return success(row.getProjectScore());
    }


    /**
     * 添加评论
     * @param comment {"projectId":1,"artistId":1,"projectComment":"123"}
     * @return
     */
    @ApiOperation("添加评论")
    @ApiResponse(code = 200, message = "添加评论")
    @PostMapping("list/comment")
    public AjaxResult comment(@RequestBody CandidateComment comment){
        if(comment!=null&&comment.getArtistId()!=null&&comment.getProjectId()!=null){
            SysArtistProject sysArtistProject = sysArtistProjectService.selectSysArtistProjectByTowId(comment.getArtistId(),comment.getProjectId());
            sysArtistProject.setProjectComment(comment.getProjectComment());
            sysArtistProjectService.updateSysArtistProject(sysArtistProject);
            return success();
        }
        return error("参数错误");
    }

    /**
     * 设置候选人状态
     * @param status {"projectId":1,"artistId":1,"status":1}
     * @return
     */
    @ApiOperation("设置候选人状态")
    @ApiResponse(code = 200, message = "设置候选人状态")
    @PostMapping("list/status")
    public AjaxResult status(@RequestBody CandidateStatus status){
        if(status!=null&& status.getArtistId()!=null&&status.getProjectId()!=null){
            SysArtistProject sysArtistProject = sysArtistProjectService.selectSysArtistProjectByTowId(status.getArtistId(),status.getProjectId());
            sysArtistProject.setPassStatus(status.getPassStatus());
            sysArtistProjectService.updateSysArtistProject(sysArtistProject);
            return success();
        }
        assert status != null;
        return error("参数错误" + status.toString());
    }

    


    /**
     * 查询项目自定义字段
     * @param id
     * @return
     */
    @ApiOperation("查询项目自定义字段")
    @ApiResponse(code = 200, message = "查询项目自定义字段")
    @GetMapping("list/project/{id}")
    public AjaxResult getListProject(@PathVariable("id") Long id){
        SysProject row = sysProjectService.selectSysProjectById(id);
        if(row!=null){
            return success(row.getProjectInfo());
        }
        return error("项目不存在");
    }

    /**
     * 查看艺人总信息
     * @param info
     * @return
     */
    @ApiOperation("查看艺人总信息")
    @ApiResponse(code = 200, message = "查看艺人总信息")
    @PostMapping("list/allInfo")
    public AjaxResult getListProject(@RequestBody CandidateScoreInfo info){
        SysArtistProject sysArtistProject = sysArtistProjectService.selectSysArtistProjectByTowId(info.getArtistId(),info.getProjectId());
        SysArtistProject project = sysArtistProjectService.selectSysArtistProjectList(sysArtistProject).get(0);
        SysArtist artist = sysArtistService.selectSysArtistById(info.getArtistId());
        List<SysArtistExt> exts = sysArtistExtMapper.selectSysArtistExtByArtistId(info.getArtistId());
        if(project!=null&&artist!=null){
            AjaxResult res = success();
            res.put("projectInfo",project.getProjectInfo());
            res.put("projectScope",project.getProjectScore());
            res.put("artis",artist);
            res.put("exts",exts);
            return success();
        }
        return error("项目不存在");
    }



}


